package com.magenta.maxoptra.abstractions;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.tools.JavaFileObject;

import com.magenta.maxoptra.abstractions.util.Types;

@SupportedAnnotationTypes("javax.ejb.Local")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class LocalAnnotationProcessor extends AbstractProcessor {

	@Override
	public boolean process(Set<? extends TypeElement> annotations,
			RoundEnvironment roundEnv) {
		for (TypeElement typeElement : annotations) {
			for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
				//this.processingEnv.getMessager().printMessage(
				//		Diagnostic.Kind.ERROR, "Hallo Welt!", element);
	            try {
	                System.out.format("Test Processor Running%n");
	            	String packageName = Types.getPackageName(element);
	            	String className = Types.getClassName(element);
	            	String pureClassName = className.replaceFirst(packageName, "");
	            	String generatedClassName = pureClassName.replaceAll("\\.", "") + "Proxy";
	            	@SuppressWarnings("unchecked")
					List<AnnotationValue> interfaces = (List<AnnotationValue>) Types.getAnnotationFieldValue(element, typeElement, "value");
	            	for ( AnnotationValue i : interfaces ) {
	            		if ( i.getValue() instanceof DeclaredType ) {
	            			DeclaredType interfaceType = (DeclaredType) i.getValue();
	            			System.out.println(interfaceType);// i instanceof DeclaredType//Types.getPackageName(interfaceType)
	            		}
	            	}
	            	//typeElement.getEnclosedElements().get(0)
	                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(packageName + "." + generatedClassName);
	                PrintWriter out = new PrintWriter(jfo.openWriter());
	                if ( !packageName.isEmpty() ) {
	                	out.println("package " + packageName + ";");
	                }
	                out.println("public class " + generatedClassName + " {");
	                out.println("    public final static String HELLO=\"Kia Ora\";");
	                out.println("}");
	                out.close();
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }

			}
		}
		return true;
	}

}
